import Notify from '../../miniprogram_npm/@vant/weapp/notify/notify';
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog';
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';
import utils from '../../utils/util.js'
const app = getApp()
const db = wx.cloud.database();
const _ = db.command;

// const creat_date_time = date.getFullYear() + '/' + (date.getMonth() + 1) + '/' + date.getDate() + ' ' + date.getHours() + ':' + date.getMinutes()  
Page({
 
  data: {
    loading: true,
    totalTime: 0,
    show_day: false,
    show_values: false,
    show_seat_tag: false,
    isShowStartTimePicker: false,
    isShowEndTimePicker: false,
    timePickerColumns: [],
    seat_information: [],
    show_seat: [],
    appointment_list: [],
    seat_list: [],
    appointment: [],
    day_value: "今天",
    dateformat: "请选择时间",
    finalSubmitForm: {
      name: null,
      start_time: "请选择开始时间",
      end_time: "请选择结束时间",
      position: '请选择座位',
      floor: null,
      isCheck: false,
      seat_id: ""
    },
  },
  show_seat_information() {
    this.setData({
      show_seat_tag: true,
      show_values: false
    })
  },
  time_compare(s, e, list) {
    var status = true
    var date_s
    var date_e
    for (let i = 0; i < list.length; i++) {
      date_s = new Date(list[i].start_time)
      date_e = new Date(list[i].end_time)
      if ((s > date_s && s < date_e) || (e > date_s && e < date_e) || (s <= date_s && e >= date_e)) {
        status = false
      }
    }
    return status
  },
  showDay() {
    this.setData({
      show_day: true
    })
  },
  onDaySelect(e) {
    let now = new Date()
    if (e.detail.name == "今天") {
      if (this.data.finalSubmitForm.start_time != "请选择开始时间") {
        let startDate = new Date(this.data.finalSubmitForm.start_time);
        startDate.setDate(now.getDate())
        //判断另一天
        if (this.data.finalSubmitForm.end_time != "请选择结束时间") {
          let endDate = new Date(this.data.finalSubmitForm.end_time);
          endDate.setDate(now.getDate())
          this.setData({
            "finalSubmitForm.end_time": utils.formatTime(endDate)
          })
        }
        this.setData({
          "finalSubmitForm.start_time": utils.formatTime(startDate)
        })
      }
    } else {
      if (this.data.finalSubmitForm.end_time != "请选择结束时间") {
        let tomorrow = new Date(now.valueOf() + 1 * 24 * 60 * 60 * 1000)
        let endDate = new Date(this.data.finalSubmitForm.end_time);
        endDate.setDate(tomorrow.getDate())
        if (this.data.finalSubmitForm.start_time != "请选择开始时间") {
          let startDate = new Date(this.data.finalSubmitForm.start_time);
          startDate.setDate(tomorrow.getDate())
          this.setData({
            "finalSubmitForm.start_time": utils.formatTime(startDate)
          })
        } 
        this.setData({
          "finalSubmitForm.end_time": utils.formatTime(endDate)
        })
      }
    }


    if (this.data.finalSubmitForm.end_time != "请选择结束时间" && this.data.finalSubmitForm.start_time != "请选择开始时间") {
      //获取时间跨度
      this.setData({
        dateformat: e.detail.name + new Date(this.data.finalSubmitForm.start_time).getHours() + ":" + new Date(this.data.finalSubmitForm.start_time).getMinutes() + "-" + new Date(this.data.finalSubmitForm.end_time).getHours() + ":" + new Date(this.data.finalSubmitForm.end_time).getMinutes()
      })
    }





    this.setData({
      day_value: e.detail.name
    })
    this.setData({
      show_day: false
    })
    this.refreshSeat()
  },
  showStartTimePicker() {
    if (this.data.day_value == '今天'){
      let localTime = new Date()
      let checkTime  = new Date(localTime.getFullYear() + '/' +  (localTime.getMonth()+1) + '/' + localTime.getDate() + ' '+ '20:00')
     
      if(localTime >checkTime){
        Dialog.alert({
          message: '今天已无法预约,请选择明天',
        })
      }else{
        this.setData({
          isShowStartTimePicker: true
        })
      }
    }else{
      this.setData({
        isShowStartTimePicker: true
      })
    } 
  },
  showEndTimePicker() {
    if(this.data.day_value == '今天'){
      let localTime = new Date()
      let checkTime  = new Date(localTime.getFullYear() + '/' +  (localTime.getMonth()+1) + '/' + localTime.getDate() + ' '+ '20:00')
    
      if(localTime >checkTime){
        Dialog.alert({
          message: '今天已无法预约,请选择明天',
        })
      }else{
        this.setData({
          isShowEndTimePicker: true
        })
      }
    }else{
      this.setData({
        isShowEndTimePicker: true
      })
    }
  },
  onStartTimeChange(e) {
    let date = new Date()
    if (this.data.day_value != "今天") {
      date = new Date(date.valueOf() + 1 * 24 * 60 * 60 * 1000)
    }
    date.setHours(e.detail.value[0])
    date.setMinutes(e.detail.value[1])
    let start = new Date(date)
    if (this.data.finalSubmitForm.end_time != "请选择结束时间") {
      this.setData({
        dateformat: this.data.day_value + start.getHours() + ":" + start.getMinutes() + "-" + new Date(this.data.finalSubmitForm.end_time).getHours() + ":" + new Date(this.data.finalSubmitForm.end_time).getMinutes()
      })
    }
    this.setData({['finalSubmitForm.start_time']: utils.formatTime(start)})
    this.totalTime()
    this.refreshSeat()
  },
  onEndTimeChange(e) {
    let date = new Date()
    if (this.data.day_value != "今天") {
      date = new Date(date.valueOf() + 1 * 24 * 60 * 60 * 1000)
    }
    date.setHours(e.detail.value[0])
    date.setMinutes(e.detail.value[1])
    let end = new Date(date)
    if (this.data.finalSubmitForm.start_time != "请选择开始时间") {
      this.setData({
        dateformat: this.data.day_value + new Date(this.data.finalSubmitForm.start_time).getHours() + ":" + new Date(this.data.finalSubmitForm.start_time).getMinutes() + "-" + end.getHours() + ":" + end.getMinutes()
      })
    }
    this.setData({
      ['finalSubmitForm.end_time']: utils.formatTime(end)
    })
    this.totalTime()
    this.refreshSeat()
  },
  onCancelEndTimePicked() {
    let startTime = new Date(this.data.finalSubmitForm.start_time)
    let endlTime = new Date(this.data.finalSubmitForm.end_time)
  
    if (this.data.finalSubmitForm.start_time != '请选择开始时间' && endlTime < startTime){
      Dialog.alert({
        message: '开始时间小于结束时间,请选择明天',
      })
    }
    this.setData({
      isShowEndTimePicker: false
    })
  },
  onConfirmEndTimePicked() {
    let startTime = new Date(this.data.finalSubmitForm.start_time)
    let endlTime = new Date(this.data.finalSubmitForm.end_time)
  
    if (this.data.finalSubmitForm.start_time != '请选择开始时间' && endlTime < startTime){
      Dialog.alert({
        message: '开始时间小于结束时间',
      })
    }
    this.setData({
      isShowEndTimePicker: false
    })
  },
  onConfirmStartTimePicked(e) {
    let startTime = new Date(this.data.finalSubmitForm.start_time)
    let localTime = new Date()
  
    if (this.data.finalSubmitForm.start_time != '请选择开始时间' && localTime > startTime){
      Dialog.alert({
        message: '开始时间小于当前时间',
      })
    }
    
    this.setData({
      isShowStartTimePicker: false
    })
  },
  onCancelStartTimePicked() {
    let startTime = new Date(this.data.finalSubmitForm.start_time)
    let localTime = new Date()
   
    if (this.data.finalSubmitForm.start_time != '请选择开始时间' && localTime > startTime){
      Dialog.alert({
        message: '开始时间小于当前时间',
      })
    }
    this.setData({
      isShowStartTimePicker: false
    })
  },
  // onChange_day(e) {
  //   this.setData({
  //     day_value_: e.detail.value
  //   })
  // },
  //计算时长
  totalTime() {
    if (this.data.finalSubmitForm.start_time != '请选择开始时间' && this.data.finalSubmitForm.end_time != '请选择结束时间') {

      let start = new Date(this.data.finalSubmitForm.start_time)
      let end = new Date(this.data.finalSubmitForm.end_time)
      let total = (end - start) / 100 / 6

      if (total >= 0) {
        this.setData({
          totalTime: total
        })
      } else {
        this.setData({
          totalTime: 0
        })
      }
    }
  },

  myTip(text) {
    Notify({
      type: 'success',
      message: text,
      duration: 1000,
    });
  },
  onLoad: async function (options) {
    this.setData({
      loading: true,
      ['finalSubmitForm.name']: app.globalData.name,
      ['finalSubmitForm.floor']: options.floor,
      appointment: [],
      timePickerColumns: [{
        values: this.getHoures(),
        className: "时"
      }, {
        values: this.getMinutes(),
        className: "分"
      }],
    })
    // //获取所有座位信息
    let count_seat = (await db.collection("seat_position_form").count()).total
    let all_seat = []
    for (let i = 0; i < count_seat; i += 20) {
      let list_seat = await db.collection("seat_position_form").where({
        floor: this.data.finalSubmitForm.floor
      }).skip(i).get()
      all_seat = all_seat.concat(list_seat.data)
    }
    //获取所有预约信息
    let count_app = (await db.collection("appointment_time").count()).total
    let appointment_list = []
    for (let i = 0; i < count_app; i += 20) {
      let list_app = await db.collection("appointment_time").where({
        floor: this.data.floor
      }).skip(i).get()
      appointment_list = appointment_list.concat(list_app.data)
    }
    this.setData({
      appointment_list: appointment_list,
      seat_list: all_seat
    })
    this.refreshSeat()
    

    //监控公告
    let titleBar = this.selectComponent("#titleBar")
    db.collection("notifyMessage").watch({
      onChange: res=>{
      
          if(res.docChanges.length == 0){
              titleBar.update("暂无通知")
          }else if(res.docChanges[0].dataType == 'init'){
              if(res.docs.length != 0){
                  titleBar.update(res.docs[res.docs.length -1].message)
              }else{
                  titleBar.update("暂无通知")
              }
          }else if(res.docChanges[0].dataType == 'add'){
              titleBar.update("新通知："+res.docChanges[0].doc.message)
          }else if(res.docChanges[0].dataType == 'remove'){
              if(res.docs.length != 0){
                  titleBar.update(res.docs[res.docs.length -1].message)
              }else{
                  titleBar.update("暂无通知")
              }
          }
      },
      onError:res => {
      }
    })



  },
  refreshSeat() {
    let seat_list = this.data.seat_list
    let app_list = this.data.appointment_list
    let seat_app_list = []
    let s = new Date(this.data.finalSubmitForm.start_time);
    let e = new Date(this.data.finalSubmitForm.end_time);
    let appointment = []
    for (let i = 0; i < seat_list.length; i++) {
      seat_app_list = []
      for (let j = 0; j < app_list.length; j++) {
        if (seat_list[i].position === app_list[j].position) {
          seat_app_list.push(app_list[j])
        }
      }
      let status = this.time_compare(s, e, seat_app_list)
      seat_list[i].status = status
      appointment.push(seat_list[i])
    }
    this.setData({ //会自动更新appointment
      loading: false,
      appointment: appointment
    })
  },
  onShow: function () {

  },

  onShareAppMessage: function () {},
  onClickSeat(event) {
    //修改背景颜色
    let that = this
    that.data.appointment.forEach(function (v, i, a) {
      that.setData({
        [`appointment[${i}].color`]: 'white'
      })
      if (that.data.appointment[i].position == event.currentTarget.id) {
        that.setData({
          [`appointment[${i}].color`]: '#FC9D99'
        })
      }
    })
    this.setData({
      show_seat: []
    })
    db.collection("appointment_time").where({ //获取当前座位信息
      'position': event.currentTarget.id
    }).get().then(res => {
      this.setData({
        seat_information: res.data
      });
      for (let i = 0; i < res.data.length; i++) {
        let s = new Date(res.data[i].start_time)
        let e = new Date(res.data[i].end_time)
        let day_ = '';
        if (s.getDate() == new Date().getDate()) {
          day_ = '今天'
        } else {
          day_ = '明天'
        }
        let seat_ = {
          day: day_,
          start: s.getHours() + ':' + s.getMinutes(),
          end: e.getHours() + ':' + e.getMinutes()
        }
        let show = this.data.show_seat;
        show.push(seat_)
        this.setData({
          show_seat: show
        })
      }
    })
    this.setData({
      ['finalSubmitForm.position']: event.currentTarget.id,
      show_values: true,
      ["finalSubmitForm.seat_id"]: event.currentTarget.dataset.item._id
    });
  },
  // //提交预约触发
  async submint() { //提交预约
    let date = new Date()
    let count = await db.collection("appointment_time").where({
      _openid: app.globalData.openId
    }).count()
    let s = new Date(this.data.finalSubmitForm.start_time);
    let e = new Date(this.data.finalSubmitForm.end_time);
    let list = this.data.seat_information;
    if (count.total >= 2) { //判断预约次数
      Dialog.alert({
        message: '预约次数到达上限，上限为2次'
      })
    } else if (s > e || s < date) { //判断预约时间是否错误
      Dialog.alert({
        title: '时间选择错误',
        message:'请检查开始时间是否大于结束时间，或者今天当前时间不在书馆预约时段内。'
      })
    } else if (!this.time_compare(s, e, list)) { //判断预约时间是否重复
      Dialog.alert({
        message:  this.data.finalSubmitForm.position + '号座位 ' + '此时间段以被预约',
      })
    } else { //最终提交
      Dialog.confirm({
        title: this.data.finalSubmitForm.floor + this.data.finalSubmitForm.position + '号位置',
        message: '开始时间' + this.data.finalSubmitForm.start_time + '-结束时间' + this.data.finalSubmitForm.end_time,
      }).then(() => {
        this.setData({
          'finalSubmitForm.time': utils.formatTime(new Date())
        })
        db.collection("appointment_time").add({
          data: this.data.finalSubmitForm
        }).then(res => { //预约成功更改当前用户预约状态
          this.myTip();
          wx.navigateBack()
        })
      })
    }
  },
  onClose() {
    this.setData({
      show_seat_tag: false,
      show_values: true
    });
  },
  getHoures() {
    let result = []
    for (let i = 8; i < 20; i++) {
      result.push(i)
    }
    return result
  },
  getMinutes() {
    let result = []
    for (let i = 0; i < 60; i += 10) {
      result.push(i)
    }
    return result
  },
})